package org.bao.bestmatch.ui;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.util.LinkedList;

import org.bao.bestmatch.Runner;
import org.bao.bestmatch.model.TFT_CFPair;
import org.bao.bestmatch.utils.Writer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;

/**
 * UI of this program, requires ECLIPSE-SWT.
 * @author baoxiwu<bb@feijiao.info>,Cell&Module,BOE DT
 * @version 0.9.0
 * @since 2010-11-23
 * @license LGPL
 * 
 */
public class Frame {
	//CONST VARS FOR DISPLAY IN UI.
	private final String LABEL_TEXT_CF_ID = "CF ID:";
	private final String LABEL_TEXT_TFT_ID = "TFT ID:";
	private final String LABEL_TEXT_WRITE_2_FILE = "写入文件";
	private final String LABEL_TEXT_YIELD_RATE = "良率";
	
	private final String BUTTON_TEXT_CHOOSE_FILE = "选择文件";
	private final String BUTTON_TEXT_OK = "确定";
	private final String BUTTON_TEXT_SEARCH = "查找";
	
	
	private final String MESSAGE_BOX_TEXT_ERROR = "出错了！";
	private final String MESSAGE_BOX_TEXT_WARNING = "注意了！";
	private final String MESSAGE_BOX_MESSAGE_NOT_SELECT_FILE = "未选择文件！";
	private final String MESSAGE_BOX_MESSAGE_DATA_ERROR = "数据文件错误，请检查！";
	private final String MESSAGE_BOX_MESSAGE_RUN_FIRST = "请先进行匹配再查找！";
	private final String MESSAGE_BOX_MESSAGE_INPUT_TFT_OR_CF_ID = "请输入TFT或CF其中之一的ID！";
	private final String MESSAGE_BOX_MESSAGE_MATCH_NOT_FOUND = "未查找到结果，请检查输入是否正确";
	private final String MESSAGE_BOX_MESSAGE_MATCH_FOUND = "配对的TFT&CF为：";
	
	
	private final String SHELL_TEXT_TITLE = "TFT/CF最佳配对";
	private final int SHELL_SIZE_HEIGHT = 500;
	private final int SHELL_SIZE_WIDTH = 512;
	
	
	private final String TABLE_COLUMN_TEXT_NUMBER = "序号";
	private final String TABLE_COLUMN_TEXT_CF_CST_ID = "CF_CST_ID";
	private final String TABLE_COLUMN_TEXT_CF_GLS_ID = "CF_GLS_ID";
	private final String TABLE_COLUMN_TEXT_TFT_CST_ID = "TFT_CST_ID";
	private final String TABLE_COLUMN_TEXT_TFT_GLS_ID = "TFT_GLS_ID";
	
	private final String TABLE_COLUMN_TEXT_YIELD_RATE_ITEM = "项目";
	private final String TABLE_COLUMN_TEXT_GOOD_NUMBER = "良品数";
	private final String TABLE_COLUMN_TEXT_TOTAL_NUMBER = "总数";
	private final String tABLE_COLUMN_TEXT_YIELD_RATE = "良率";
	
	private final int TABLE_SIZE_HEIGHT = 220 ;
	
	
	private final String TIP_TEXT_BUTTON_SEARCH = "输入TFT/CF的[CST_ID/GLS_ID]查找配对信息";
	
	private final int TEXT_INPUT_LIMIT = 25;
	
	private final int TEXT_SIZE_HEIGHT = 20;
	private final int TEXT_SIZE_WIDTH = 150;
	
	private final int TABLE_COLUMN_WIDTH = 106;
	
	private final String IMAGE_FILE_PATH = "imgs/dt_logo.png";
	
	
	public void run() {
		Display display = new Display();
		final Shell shell = new Shell(display, SWT.CLOSE|SWT.MIN);

		Image image = new Image(display, Frame.class.getResourceAsStream(IMAGE_FILE_PATH));
		
		shell.setImage(image);
		shell.setText(this.SHELL_TEXT_TITLE);
		
		//Layout settings
		GridLayout grid = new GridLayout();
		grid.numColumns = 6;
		grid.verticalSpacing = 2;
		grid.horizontalSpacing = 5;
		
		shell.setLayout(grid);
		
		
		//text for display selected file path
		final Text text_chooseFile = new Text(shell,SWT.READ_ONLY | SWT.BORDER);
		GridData gridData = new GridData();
		gridData.heightHint = this.TEXT_SIZE_HEIGHT;
		gridData.widthHint = this.TEXT_SIZE_WIDTH;
		text_chooseFile.setLayoutData(gridData);
		
		//button for select a file.
		Button button_chooseFile = new Button(shell,SWT.PUSH);
		button_chooseFile.setText(this.BUTTON_TEXT_CHOOSE_FILE);
		
		button_chooseFile.addSelectionListener(new SelectionAdapter(){
			public void widgetSelected(SelectionEvent e){
				FileDialog dialog_fileChoose = new FileDialog(shell,SWT.SINGLE); 
				
				dialog_fileChoose.setFilterNames(new String[]{"*.xls","所有文件"});
				dialog_fileChoose.setFilterExtensions(new String[]{"*.xls","*.*"});
				
				String path = dialog_fileChoose.open();
				
				if(path != null){
					text_chooseFile.setText(path);
				}
			}
		});
		
		
		//a separator label
		Label label_separator_vertical = new Label(shell, SWT.SEPARATOR | SWT.VERTICAL);
		gridData = new GridData(GridData.FILL_BOTH);
		gridData.verticalSpan = 2;
		label_separator_vertical.setLayoutData(gridData);
		
		Label label_tft_id = new Label(shell,SWT.NONE);
		label_tft_id.setText(this.LABEL_TEXT_TFT_ID);
		
		//text for inputing TFT id
		final Text text_TFT_ID = new Text(shell, SWT.BORDER);
		text_TFT_ID.setTextLimit(this.TEXT_INPUT_LIMIT);
		//text_TFT_ID.setText("TFT_ID");
		gridData = new GridData();
		gridData.heightHint = this.TEXT_SIZE_HEIGHT;
		gridData.widthHint = this.TEXT_SIZE_WIDTH;
		text_TFT_ID.setLayoutData(gridData);
		
		
		//button for search
		Button button_search = new Button(shell,SWT.PUSH);
		button_search.setText(this.BUTTON_TEXT_SEARCH);
		button_search.setToolTipText(this.TIP_TEXT_BUTTON_SEARCH);
		gridData = new GridData();
		gridData.verticalSpan = 2;
		button_search.setLayoutData(gridData);
		
		
		
		//check button for writing into files.
		final Button button_write2file = new Button(shell,SWT.CHECK);
		button_write2file.setText(this.LABEL_TEXT_WRITE_2_FILE);
		button_write2file.setSelection(true);
		
		//button ok.
		Button button_ok = new Button(shell,SWT.PUSH);
		button_ok.setText(this.BUTTON_TEXT_OK);
		

		Label label_cf_id = new Label(shell,SWT.NONE);
		label_cf_id.setText(this.LABEL_TEXT_CF_ID);
		
		//text for inputing TFT id
		final Text text_CF_ID = new Text(shell, SWT.BORDER);
		text_CF_ID.setTextLimit(this.TEXT_INPUT_LIMIT);
		//text_CF_ID.setText("CF_ID");
		gridData = new GridData();
		gridData.heightHint = this.TEXT_SIZE_HEIGHT;
		gridData.widthHint = this.TEXT_SIZE_WIDTH;
		text_CF_ID.setLayoutData(gridData);
		
		
		//another separator
		Label label_separator_horizontal = new Label(shell, SWT.SEPARATOR | SWT.HORIZONTAL);
		gridData = new GridData();
		gridData.horizontalSpan = 6;
		gridData.horizontalAlignment = SWT.FILL;
		label_separator_horizontal.setLayoutData(gridData);
		
		
		
		Label label_yield_rate = new Label(shell,SWT.NONE);
		label_yield_rate.setText(this.LABEL_TEXT_YIELD_RATE);
		
		//text for inputing TFT id
		final Text text_yield_rate = new Text(shell, SWT.BORDER | SWT.READ_ONLY);
		text_yield_rate.setTextLimit(this.TEXT_INPUT_LIMIT);
		//text_yield_rate.setText("TFT_ID");
		gridData = new GridData();
		//gridData.horizontalSpan = 4;
		gridData.heightHint = this.TEXT_SIZE_HEIGHT;
		gridData.widthHint = this.TEXT_SIZE_WIDTH /3;
		text_yield_rate.setLayoutData(gridData);
		
		
		
		
		
		
		
		
		//another separator
		Label label_separator_horizontal_2 = new Label(shell, SWT.SEPARATOR | SWT.HORIZONTAL);
		gridData = new GridData();
		gridData.horizontalSpan = 6;
		gridData.horizontalAlignment = SWT.FILL;
		label_separator_horizontal_2.setLayoutData(gridData);
		
		
		
		
		
		
		
		final Table table_yield_rate = new Table(shell, SWT.None);
		table_yield_rate.setHeaderVisible(true);
		table_yield_rate.setLinesVisible(true);
		
		
		gridData = new GridData();
		gridData.horizontalSpan = 6;
		gridData.heightHint = this.TABLE_SIZE_HEIGHT/3;
		
		gridData.verticalAlignment = SWT.FILL;
		gridData.horizontalAlignment = SWT.FILL;
		table_yield_rate.setLayoutData(gridData);
		
		TableColumn tc_yield_rate_item = new TableColumn(table_yield_rate, SWT.CENTER);
		TableColumn tc_good_number = new TableColumn(table_yield_rate, SWT.CENTER);
		TableColumn tc_total_number = new TableColumn(table_yield_rate, SWT.CENTER);
		TableColumn tc_yield_rate = new TableColumn(table_yield_rate, SWT.CENTER);
		
		tc_yield_rate_item.setText(this.TABLE_COLUMN_TEXT_YIELD_RATE_ITEM);
		tc_good_number.setText(this.TABLE_COLUMN_TEXT_GOOD_NUMBER);
		tc_total_number.setText(this.TABLE_COLUMN_TEXT_TOTAL_NUMBER);
		tc_yield_rate.setText(this.tABLE_COLUMN_TEXT_YIELD_RATE);
		
		tc_yield_rate_item.setWidth(TABLE_COLUMN_WIDTH);
		tc_good_number.setWidth(TABLE_COLUMN_WIDTH);
		tc_total_number.setWidth(TABLE_COLUMN_WIDTH);
		tc_yield_rate.setWidth(TABLE_COLUMN_WIDTH);
		
		
		
		
		
		
		
		//another separator
		Label label_separator_horizontal_3 = new Label(shell, SWT.SEPARATOR | SWT.HORIZONTAL);
		gridData = new GridData();
		gridData.horizontalSpan = 6;
		gridData.horizontalAlignment = SWT.FILL;
		label_separator_horizontal_3.setLayoutData(gridData);
		
		
		
		
		
		//table to display matched result.
		final Table table_match = new Table(shell, SWT.NONE);
		table_match.setHeaderVisible(true);
		table_match.setLinesVisible(true);
		
		gridData = new GridData();
		gridData.horizontalSpan = 6;
		gridData.heightHint = this.TABLE_SIZE_HEIGHT;
		
		gridData.verticalAlignment = SWT.FILL;
		gridData.horizontalAlignment = SWT.FILL;
		table_match.setLayoutData(gridData);
		
		
		TableColumn tc_Number = new TableColumn(table_match, SWT.CENTER);
		TableColumn tc_CF_CST_id = new TableColumn(table_match,SWT.CENTER);
		TableColumn tc_CF_GLS_id = new TableColumn(table_match,SWT.CENTER);
		TableColumn tc_TFT_CST_id = new TableColumn(table_match,SWT.CENTER);
		TableColumn tc_TFT_GLS_id = new TableColumn(table_match,SWT.CENTER);
		
		
		tc_Number.setText(TABLE_COLUMN_TEXT_NUMBER);
		tc_CF_CST_id.setText(this.TABLE_COLUMN_TEXT_CF_CST_ID);
		tc_CF_GLS_id.setText(this.TABLE_COLUMN_TEXT_CF_GLS_ID);
		tc_TFT_CST_id.setText(this.TABLE_COLUMN_TEXT_TFT_CST_ID);
		tc_TFT_GLS_id.setText(this.TABLE_COLUMN_TEXT_TFT_GLS_ID);
		
		tc_Number.setWidth(this.TABLE_COLUMN_WIDTH/2);
		tc_CF_CST_id.setWidth(this.TABLE_COLUMN_WIDTH);
		tc_CF_GLS_id.setWidth(this.TABLE_COLUMN_WIDTH);
		tc_TFT_CST_id.setWidth(this.TABLE_COLUMN_WIDTH);
		tc_TFT_GLS_id.setWidth(this.TABLE_COLUMN_WIDTH);
		
		
		
		button_ok.addSelectionListener(new SelectionAdapter(){
			public void widgetSelected(SelectionEvent e){
				if(text_chooseFile.getText().length()  <= 0){
					MessageBox mb = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
					mb.setText(MESSAGE_BOX_TEXT_WARNING);
					mb.setMessage(MESSAGE_BOX_MESSAGE_NOT_SELECT_FILE);
					mb.open();
					
					return;
				}
				
				if(Runner.run(text_chooseFile.getText())){
					//remove old data
					table_match.removeAll();
					table_yield_rate.removeAll();
					
					
					TableItem ti = null;
					LinkedList<TFT_CFPair> pair = Runner.pair;
					
					for(int i = 0; i < pair.size(); i ++){
						ti = new TableItem(table_match, SWT.None);
						ti.setText(new String[]{String.valueOf(i + 1) ,pair.get(i).getCF().getCst_id(), pair.get(i).getCF().getGlass_id(), 
								pair.get(i).getTFT().getCst_id(), pair.get(i).getTFT().getGlass_id()});
					}
					
					text_yield_rate.setText(Runner.result[7]);
					
					
					ti = new TableItem(table_yield_rate, SWT.None);
					ti.setText(new String[]{"CF", Runner.result[1], Runner.result[0], Runner.result[2]});
					
					ti = new TableItem(table_yield_rate, SWT.None);
					ti.setText(new String[]{"TFT", Runner.result[3], Runner.result[0], Runner.result[4]});
					
					ti = new TableItem(table_yield_rate, SWT.None);
					ti.setText(new String[]{"Cell", Runner.result[5], Runner.result[0], Runner.result[6]});
					
					
					
					
					
					if(button_write2file.getSelection()){
						String str = "";
						
						for(int i = 0; i < pair.size(); i++){
							str += ("[" + (i + 1) + "]\r\n" + pair.get(i).toString());
						}
						
						Writer.out(str);
					}
				}
				else{
					MessageBox mb = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
					mb.setText(MESSAGE_BOX_TEXT_ERROR);
					mb.setMessage(MESSAGE_BOX_MESSAGE_DATA_ERROR);
					mb.open();
					
					return;
				}
			}
		});
		
		
		button_search.addSelectionListener(new SelectionAdapter(){
			public void widgetSelected(SelectionEvent e){
				if(text_TFT_ID.getText().length() <= 0 && text_CF_ID.getText().length() <= 0){
					MessageBox mb = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
					mb.setText(MESSAGE_BOX_TEXT_WARNING);
					mb.setMessage(MESSAGE_BOX_MESSAGE_INPUT_TFT_OR_CF_ID);
					mb.open();
					
					return;
				}
				else
				if(text_TFT_ID.getText().length() > 0 && text_CF_ID.getText().length() > 0){
					MessageBox mb = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
					mb.setText(MESSAGE_BOX_TEXT_ERROR);
					mb.setMessage(MESSAGE_BOX_MESSAGE_INPUT_TFT_OR_CF_ID);
					mb.open();
					
					return;
				}
				else{
					if(Runner.pair == null){
						MessageBox mb = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
						mb.setText(MESSAGE_BOX_TEXT_WARNING);
						mb.setMessage(MESSAGE_BOX_MESSAGE_RUN_FIRST);
						mb.open();
						
						return;
					}
					else{
						TFT_CFPair pair = null;
						
						if(text_TFT_ID.getText().length() > 0){
							String[] ids = text_TFT_ID.getText().split("/");
							
							for(int i = 0; i < Runner.pair.size(); i++){
								if(Runner.pair.get(i).getTFT().getCst_id().equals(ids[0]) 
										&& Runner.pair.get(i).getTFT().getGlass_id().equals(ids[1])){
									pair = Runner.pair.get(i);
								}
							}
							
						}
						else{
							String[] ids = text_CF_ID.getText().split("/");
							
							for(int i = 0; i < Runner.pair.size(); i++){
								if(Runner.pair.get(i).getCF().getCst_id().equals(ids[0]) 
										&& Runner.pair.get(i).getCF().getGlass_id().equals(ids[1])){
									pair = Runner.pair.get(i);
								}
							}
						}
						
						if(pair != null){
							MessageBox mb = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
							mb.setText(MESSAGE_BOX_TEXT_WARNING);
							mb.setMessage(MESSAGE_BOX_MESSAGE_MATCH_FOUND + "\n\t" + pair.getCF() + 
									"\n\t" + pair.getTFT());
							mb.open();
							
							return;
						}
						else{
							MessageBox mb = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
							mb.setText(MESSAGE_BOX_TEXT_WARNING);
							mb.setMessage(MESSAGE_BOX_MESSAGE_MATCH_NOT_FOUND);
							mb.open();
							
							return;
						}
						
					}
				}	
			}
		});
		
		
		//set SHELL location
		Dimension  dim = Toolkit.getDefaultToolkit().getScreenSize();
		shell.setLocation((int)(dim.getWidth() - this.SHELL_SIZE_WIDTH)/2, (int)(dim.getHeight() - this.SHELL_SIZE_HEIGHT)/2);
		
		shell.setSize(this.SHELL_SIZE_WIDTH, this.SHELL_SIZE_HEIGHT);
		shell.open();
		
		while(!shell.isDisposed()){
			if(!display.readAndDispatch()){
				display.sleep();
			}
		}
		
		display.dispose();
	}
	
	
	public static void main(String[] args){
		Frame f = new Frame();
		f.run();
	}
}
